/*
 * 文 件 名 : InputBarListener.java
 * 版    权 : China Machi.Co.,Ltd.Copyright 2009-2011.All rights reserved
 * 描    述 : <描述>
 * 修 改 人 : lixg
 * 修改时间 : 2012-8-22
 * 跟踪单号 : <跟踪单号>
 * 修改单号 : <修改单号>
 * 修改内容 : <修改内容>
 */
package com.fire8.dolphin.ui;

import java.io.File;
import java.io.IOException;

import android.content.Context;
import android.media.MediaRecorder;
import android.os.Environment;
import android.os.Handler;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnLongClickListener;
import android.view.View.OnTouchListener;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.Toast;

import com.fire8.dolphin.utils.StringUtil;

/**
 * 底部输入栏按钮事件处理类
 * <功能详细描述>
 *
 * @author  lixg
 * @version [版本号,2012-8-22]
 * @see     [相关类/方法]
 * @since   [产品/模块]
 */
public class InputBarListener implements OnClickListener
{
    private final String TAG="dolphin";
    private Handler mHandler;
    private Context context;
    LayoutInflater factory;
    private LinearLayout layoutInputContext;
    private MediaRecorder mRecorder = null;
    private File mRecAudioPath;
    private File mRecAudioFile;
    public InputBarListener(Context c,LinearLayout layout,Handler handler)
    {
        context = c;
        layoutInputContext = layout;
        mHandler = handler;
        factory = LayoutInflater.from(context);
    }
    /**
     * @param v
     */
    @Override
    public void onClick(View v)
    {
        if(R.id.btn_input_face == v.getId())
        {
            inputFace(v);    
        }else if(v.getTag() != null)
        {
            layoutInputContext.removeAllViews();
            v.setTag(null);
            return;
        }
        v.setTag("a");
        switch (v.getId())
        {
            case R.id.btn_input_voice:
                inputVoice();
                break;
            
            case R.id.btn_input_doodle:
                
                break;
            case R.id.btn_input_pic:
                
                break;
            case R.id.btn_input_text:
                inputText(v);
                break;
            default:
                break;
        }
    }
    /**
     * 表情输入
     * <功能详细描述>
     * @param v [参数说明]
     *
     * @author lixg
     * @see [类、类#方法、类#成员]
     */
    private void inputFace(View v)
    {
        //EditText txtAnswer = (EditText)layoutInputContext.findViewById(R.id.txt_answer);
        Object obj =layoutInputContext.findViewById(R.id.txt_answer);
        if(obj == null)
        {
            inputText(v);
        }else
        {
            Log.i(TAG,"关闭软件键盘");
            EditText txtAnswer =(EditText)obj;
            //关闭软件键盘
            InputMethodManager imm = (InputMethodManager)context.getSystemService(Context.INPUT_METHOD_SERVICE); 
            imm.hideSoftInputFromWindow(txtAnswer.getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
        }
        
        
        //弹出表情输入窗口
        PopupFaceViewWindow editWindow = PopupFaceViewWindow.getInstall(context,mHandler);

        if (editWindow.isShowing())  
        {
            Log.i(TAG,"隐藏窗口");
            editWindow.dismiss(); 
        }
        else {  
            Log.i(TAG,"显示窗口");
            editWindow.showAsDropDown(v,0, 120);
            //editWindow.showAtLocation(layoutInputContext.findViewById(R.id.layout_answer), Gravity.RIGHT|Gravity.BOTTOM, 0,46);
        }
    }
    
    //点击录音按钮，弹出录音页面
    private void inputVoice()
    {
        View vInputType = factory.inflate(R.layout.input_type_voic, null); 
        layoutInputContext.removeAllViews();
        layoutInputContext.addView(vInputType);
        ImageButton btnRecord = (ImageButton)layoutInputContext.findViewById(R.id.btn_input_voice_record);
        btnRecord.setOnLongClickListener(new OnLongClickListener()
        {
            
            @Override
            public boolean onLongClick(View v)
            {
                startRecording();
                return false;
            }
        });
        
        btnRecord.setOnTouchListener(new OnTouchListener()
        {
            @Override
            public boolean onTouch(View v, MotionEvent event)
            {
                if(MotionEvent.ACTION_UP == event.getAction())
                {
                    //停止录音
                    stopRecording();
                    //将录音文件名传到前台
                    if(mRecAudioFile != null)
                    {
                        sendMessage(R.id.btn_input_voice, mRecAudioFile.getPath());
                    }
                    //按录音按钮隐藏
                    layoutInputContext.removeAllViews();
                }
                return false;
            }
        });
    }
    
    private void startRecording() {
        if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
                mRecAudioPath = Environment.getExternalStorageDirectory();
                File fPath = new File(mRecAudioPath.getPath() + File.separator
                                + "RecordList");
                fPath.mkdirs();
                Log.d(TAG, "创建文件夹"+fPath.getPath());
                mRecAudioFile = fPath;
        } else {
            mRecAudioFile = context.getCacheDir();    
            Log.d(TAG, "没有插卡或没有读写卡权限，创建文件夹");
        }
        try {
                mRecAudioFile = File.createTempFile(String.valueOf(System.currentTimeMillis()), ".3gp", mRecAudioFile);
                Log.d(TAG, "创建文件： "+mRecAudioFile.getPath()+" "+ mRecAudioFile.getName());
        } catch (IOException e) {
                Log.e(TAG, "mRec", e);
        }
        
        mRecorder = new MediaRecorder();
        mRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);
        mRecorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP);
        mRecorder.setOutputFile(mRecAudioFile.getPath());
        mRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);
        try {
            mRecorder.prepare();
            mRecorder.start();
            Log.d(TAG, "开始录音...");
        } catch (IOException e) {
            Log.e(TAG, "prepare() failed",e);
        }
        
        
    }
    private void stopRecording() {
        if(mRecorder == null)
            return;
        //if(mRecorder.)
        mRecorder.stop();
        mRecorder.release();
        mRecorder = null;
        Log.d(TAG, "停止录音...");
    }
    /**
     * 点击文本输入按钮
     * <功能详细描述>
     * @param v [参数说明]
     *
     * @author lixg
     * @see [类、类#方法、类#成员]
     */
    private void inputText(View v)
    {
        
        View vInputType = factory.inflate(R.layout.input_type_text, null); 
        layoutInputContext.removeAllViews();
        layoutInputContext.addView(vInputType);
        final EditText txtAnswer = (EditText)layoutInputContext.findViewById(R.id.txt_answer);
        
        Button btnSend = (Button)layoutInputContext.findViewById(R.id.btn_enter);
        btnSend.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                Log.d(TAG,"提交回复");
                String strAnswer = txtAnswer.getText().toString();
                if(StringUtil.isEmpty(strAnswer))
                {
                    Toast.makeText(context, "请输入回答内容", Toast.LENGTH_LONG).show();
                    return;
                }
                txtAnswer.setText("");
                sendMessage(R.id.btn_input_text,strAnswer);
                //关闭软件键盘
                InputMethodManager imm = (InputMethodManager)context.getSystemService(Context.INPUT_METHOD_SERVICE); 
                imm.hideSoftInputFromWindow(txtAnswer.getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
            }
        });
    }
    
    private void sendMessage(Integer msgType,Object msgObj)
    {
        mHandler.obtainMessage(msgType, msgObj).sendToTarget();
    }
    
}
